package com.dfqy.interceptor;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author oldliu
 * @since 1.0
 */

public class TimeInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long start = System.nanoTime();
        request.setAttribute("start", start);
        System.out.println("进入了handler:" + handler);
        return true;
    }

    @Override//handler执行完成后，执行此方法
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("handler:" + handler + ",返回结果是 " + modelAndView);

        long start = (Long) request.getAttribute("start");
        long end = System.nanoTime();
        long time = end - start;
        System.out.println("请求：" + request.getServletPath() + "耗时：" + time + "纳秒");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
    }
}
